/************************************************************************************/
/*  Program name CAPAPIMP_ACC_EVENT.sql                                             */
/*  Creater:  WONG Wing Kin (PCCW - UniHub)                                         */
/*************   History   *************************                                */
/* 30 NOV, 2005   WONG Wing Kin         First created                               */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPAPIMP_ACC_EVENT';

	lv_Scc_Count	NUMBER			:=	0;
	lv_Err_Count	NUMBER			:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_AP_ACCOUNTING_EVENTS;

	lv_Next_Seq_ID	NUMBER;
	lv_Source_ID	NUMBER;

BEGIN

	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	AP_ACCOUNTING_EVENTS_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT INTO CRST_AP_ACCOUNTING_EVENTS_MAP VALUES
			(
			C1.ACCOUNTING_EVENT_ID,
			lv_Next_Seq_ID
			);

			IF		C1.Source_Table	=	'AP_INVOICES'	THEN
				lv_Source_ID	:=	CAPBRIMP_MAPPING.GetAPInvoiceIDMapping(C1.SOURCE_ID);
			ELSIF	C1.Source_Table	=	'AP_CHECKS'		THEN
				lv_Source_ID	:=	CAPBRIMP_MAPPING.GetCheckIDMapping(C1.SOURCE_ID);
			END IF;

			INSERT INTO AP_ACCOUNTING_EVENTS_ALL
			VALUES
			(
			lv_Next_Seq_ID,											--ACCOUNTING_EVENT_ID,
			C1.EVENT_TYPE_CODE,
			C1.ACCOUNTING_DATE,
			C1.EVENT_NUMBER,
			C1.EVENT_STATUS_CODE,
			C1.SOURCE_TABLE,
			lv_Source_ID,											--SOURCE_ID,
			C1.CREATION_DATE,
			CAPBRIMP_COMMON.GetUser(C1.CREATED_BY_NAME),			--CREATED_BY,
			C1.LAST_UPDATE_DATE,
			CAPBRIMP_COMMON.GetUser(C1.LAST_UPDATED_BY_NAME),		--LAST_UPDATED_BY,
			C1.LAST_UPDATE_LOGIN,
			C1.PROGRAM_UPDATE_DATE,
			C1.PROGRAM_ID,
			C1.PROGRAM_APPLICATION_ID,
			C1.REQUEST_ID,
			CAPBRIMP_COMMON.GetOrgID(C1.ORG_NAME),					--ORG_ID,
			C1.CANNOT_ACCOUNT_FLAG
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;

	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);

	COMMIT;
END;
/
